// pages/category-grouping/category-grouping.js
import * as API_Shop from '../../api/shop'
import * as API_Trade from '../../api/trade.js'
import { Foundation } from '../../ui-utils/index.js'
const app = getApp();
let that;

Page({
  data: {
    goodsData: [], // 商品列表
    currentCategory: {},
    categoryFilter: false, // 分类筛选是否打开
    scrollLeft: 0,
    scrollTop: 0,
    scrollHeight: 0,
    tapData: [
      {
        'name': '综合排序',
        'type': 'def',
        'needSort': false,
        'id': 'defSort'
      },
      {
        'name': '价格',
        'type': 'price',
        'needSort': true,
        'id': 'priceSort'
      },
      {
        'name': '销量',
        'type': 'buynum',
        'needSort': true,
        'id': 'buynumSort'
      },
      {
        'name': '提货日期',
        'type': 'pick',
        'needSort': true,
        'id': 'gradeSort'
      }
    ],
    currentTap: 'def',
    params: {
      page_no: 1,
      page_size: 10,
      sort_need: false,
      sort_type: 'desc'
    },
    finished: false,
    showGoTop: false,
    pageCount: 0,
    playId: ''
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    that.setData({'params.keyword': options.keyword});
    if (options.category) {
      that.setData({'params.category': parseInt(options.category)});
    } else {
      that.setData({'params.keyword': options.keyword});
    };
    wx.getSystemInfo({
      success: function (res) {
        let query = wx.createSelectorQuery();
        query.select('.top').boundingClientRect(rect => {
          that.setData({
            scrollHeight: res.windowHeight - rect.height + "px"
          });
        }).exec();
      }
    });
  },
  onShow: function () {
    that.getGoodsList();
  },
  // 获取商品数据
  getGoodsList: function () {
    that = this;
    let { currentTap } = this.data;
    let params = JSON.parse(JSON.stringify(this.data.params));
    if (params.sort_need) {
      params.sort = `${currentTap}_${params.sort_type}`;
    };
    delete params.sort_type;
    delete params.sort_need;
    // 位置信息
    let { city } = app.globalData.locationData;
    params = {
      ...params,
      city: city
    };
    API_Shop.getShetuanGoods(params).then((res)=> {
      let _pageCount = Math.ceil(res.data_total / params.page_size);
      this.setData({ pageCount: _pageCount });
      let _list = res.data;
      if (_list && _list.length) {
        _list.forEach(item => {
          item.shetuan_price = Foundation.formatPrice(item.shetuan_price);
          item.priceInt = item.shetuan_price ? item.shetuan_price.split('.')[0] : '0';
          item.pricePoint = item.shetuan_price ? item.shetuan_price.split('.')[1] : '00';
        });
        that.setData({
          categoryFilter: false,
          goodsData: that.data.goodsData.concat(_list)
        });
      } else {
        this.setData({ finished: true });
      };
    });
    wx.setNavigationBarTitle({ title: "团购搜索结果"})
  },
  // 显示搜索页面
  showSearch () {
    let pages = getCurrentPages();
    if (pages[pages.length-2] && pages[pages.length-2].route === 'pages/search/search') {
      wx.navigateBack();
    } else {
      wx.navigateTo({
        url: '/pages/search/search?type=grouping',
      });
    }
  },
  // 图片跳转商品详情页面
  getHref(e) {
    const { video, id, sku } = e.currentTarget.dataset;
    if (video) {
      return;
    };
    wx.navigateTo({
      url: `/pages/goods/goods?goods_id=${id}&sku_id=${sku}`
    });
  },
  // 视屏显示
  playVideo: function (e) {
    const { id, index } = e.currentTarget.dataset;
    let { goodsData, playId } = this.data;
    goodsData[index].showVideo = true;
    // 暂停当前播放的视频
    if (playId) {
      let currentVideo = wx.createVideoContext(playId, this);
      currentVideo.pause();
    };
    let videoplay = wx.createVideoContext(id, this);
    videoplay.play();
    this.setData({
      goodsData,
      playId: id
    });
  },
  // 视屏继续播放
  playContinue: function (e) {
    const { id } = e.currentTarget.dataset;
    let { playId } = this.data;
    // 暂停当前播放的视频
    if (id !== playId) {
      let currentVideo = wx.createVideoContext(playId, this);
      currentVideo.pause();
      this.setData({
        playId: id
      });
    };
  },
  // 首次加入购物车
  async addCart(e) {
    wx.vibrateShort({});
    let _isLogin = await app.isLogin();
    if (!_isLogin) { return };
    const _index = e.currentTarget.dataset.index;
    let { goodsData } = this.data;
    const _sku_id = goodsData[_index].sku_id;
    const _active_id = goodsData[_index].shetuan_id;
    const _buyNum = 1; // 数量
    API_Trade.addToCart(_sku_id, _buyNum, _active_id).then(response => {
      goodsData[_index].cart_num = 1;
      this.setData({
        goodsData
      });
    });
  },
  /** 更新商品数量 */
  async handleUpdateSkuNum(e) {
    const that = this;
    const _index = e.currentTarget.dataset.index;
    const { goodsData } = this.data;
    const { sku_id, cart_num, enable_quantity } = goodsData[_index];
    const symbol = e.currentTarget.dataset.symbol;
    if (!symbol || typeof symbol !== 'string') {
      if (!e.detail.value) return
      let _num = parseInt(e.detail.value)
      if (isNaN(_num) || _num < 1) {
        wx.showToast({ title: '输入格式有误，请输入正整数', icon: 'none' })
        return
      }
      if (_num >= enable_quantity) {
        wx.showToast({ title: '超过最大库存', icon: 'none' })
        return
      }
      this.updateSkuNum({ sku_id: sku_id, num: _num })
    } else {
      wx.vibrateShort({});
      if (symbol === '-' && cart_num < 2) {
        wx.showModal({
          title: '提示',
          content: '确定要删除此商品吗?',
          confirmColor: '#f42424',
          success(res) {
            /** 删除 */
            if (res.confirm) {
              API_Trade.deleteSkuItem(sku_id, 'SHETUAN_CART').then(_ => {
                goodsData[_index].cart_num = 0;
                that.setData({
                  goodsData
                });
              }).catch()
            }
          }
        });
        return;
      };
      if (symbol === '+' && cart_num >= enable_quantity) {
        wx.showToast({ title: '超过最大库存', icon: 'none' })
        return
      };
      let _num = symbol === '+' ? cart_num + 1 : cart_num - 1
      this.updateSkuNum({ sku_id: sku_id, num: _num, index: _index })
    };
  },
  /* 更新sku数据 */
  updateSkuNum(params) {
    setTimeout(() => {
      API_Trade.updateSkuNum(params.sku_id, params.num, 'SHETUAN_CART').then(_ => {
        const { goodsData } = this.data;
        goodsData[params.index].cart_num = params.num;
        this.setData({
          goodsData
        });
      }).catch()
    }, 200)
  },
  // 加载更多
  loadMore: function (e) {
    this.setData({ 'params.page_no': this.data.params.page_no += 1});
    if (this.data.pageCount >= this.data.params.page_no) {
      this.getGoodsList();
    };
  },
  // 滚动
  scroll: function(e){
    if (e.detail.scrollTop > 200) {
      this.setData({showGoTop: true})
    } else {
      this.setData({showGoTop: false})
    }
  },
  // 返回顶部
  goTop: function(){
    this.setData({scrollTop:0})
  },
  // 排序
  openSortFilter: function (e) {
    let { sort, type } = e.currentTarget.dataset;
    this.setData({
      categoryFilter: false,
      finished: false,
      goodsData: []
    });
    let { params } = this.data;
    params.page_no = 1;
    params.sort_need = sort;
    if (this.data.currentTap === type) {
      params.sort_type = params.sort_type === 'desc' ? 'asc' : 'desc';
      this.setData({
        params
      });
    } else {
      params.sort_type = 'desc';
      this.setData({
        params,
        currentTap: type
      });
    };
    this.getGoodsList();
  }
})